//
//  TitleBarViewController.swift
//  WWDCLearn
//
//  Created by mac on 2021/6/30.
//

import Cocoa


final class TitleBarViewController:NSTitlebarAccessoryViewController {
    
    private var horizontalPositiionConstrains = [NSLayoutConstraint]()
    private var contentOfset:CGFloat = 0 {
        didSet {
            horizontalPositiionConstrains.forEach{ $0.constant = contentOfset}
        }
    }
    lazy var tabBarContainer:NSView = {
        let v = NSView()
        v.translatesAutoresizingMaskIntoConstraints = false
        return v
    }()
    lazy var statusContainer:NSView = {
        let v = NSView()
        v.translatesAutoresizingMaskIntoConstraints = false
        return v
    }()
    var statusViewController:NSViewController? {
        didSet {
           replace(child: oldValue, with: statusViewController, inContainer: statusContainer)
        }
    }
    
    var tabBar:
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    init(){
        super.init(nibName: nil, bundle: nil)
        layoutAttribute = .top
    }
    
    override func viewWillAppear() {
        super.viewWillAppear()
        guard let window = view.window else { return  }
        let windowBounds = window.convertFromScreen(window.frame)
        let localWindowBounds = view.convert(windowBounds, from: nil)
        contentOfset = localWindowBounds.midX - view.bounds.midX
    
    }
    
    func replace(child:NSViewController?, with newChild:NSViewController?, inContainer container:NSView){
        child?.view.removeFromSuperview()
        child?.removeFromParent()
        guard let newChild = newChild else { return  }
        addChild(newChild)
        newChild.view.frame = container.frame
        newChild.view.autoresizingMask = [.width,.height]
        container.addSubview(newChild.view)
    }
    
    func replace(managedView:NSView?, with newView:NSView?, inContainer container: NSView)  {
        managedView?.removeFromSuperview()
        guard let newView = newView else { return  }

        newView.frame = container.bounds
        newView.autoresizingMask = [.width,.height]
        container.addSubview(newView)
    }
    
}
